package com.hq;

import org.apache.kafka.clients.consumer.ConsumerConfig;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class GroupChatClient {
    SocketChannel socketChannel;
    Selector selector;
    String username;
    public  void connect() throws IOException {
        selector = Selector.open();
        //连接上服务器
        socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8888));
        socketChannel.configureBlocking(false);
        //注册监听写事件
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + "is ok");
        socketChannel.register(selector, SelectionKey.OP_READ);
    }

    public void readData() throws IOException {
        int count = selector.select();
        if(count>0){
            //监听到读事件 处理消息
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                if(key.isReadable()){
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer allocate = ByteBuffer.allocate(1024);
                    channel.read(allocate);
                    System.out.println(username+"收到消息"+new String(allocate.array()));
                }
                iterator.remove();
            }
        }else {
            System.out.println("没有写入数据过来");
        }

    }
    public static void main(String[] args) throws IOException {
        GroupChatClient groupChatClient = new GroupChatClient();
        groupChatClient.connect();
        new Thread(){
            @Override
            public void run() {
                while (true){
                    try {
                        //一直读取消息
                        groupChatClient.readData();
                        Thread.sleep(4000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        //设置客户端 控制台打印消息
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String next = scanner.next();
            groupChatClient.socketChannel.write(ByteBuffer.wrap(next.getBytes()));
        }
    }

}
